package com.xiaoyun.service.impl.center;

import com.github.pagehelper.PageHelper;
import com.xiaoyun.bo.center.OrderItemsCommentBO;
import com.xiaoyun.enums.YesOrNo;
import com.xiaoyun.mapper.ItemsCommentsMapperCustom;
import com.xiaoyun.mapper.OrderItemsMapper;
import com.xiaoyun.mapper.OrderStatusMapper;
import com.xiaoyun.mapper.OrdersMapper;
import com.xiaoyun.pojo.OrderItems;
import com.xiaoyun.pojo.OrderStatus;
import com.xiaoyun.pojo.Orders;
import com.xiaoyun.service.center.MyCommentService;
import com.xiaoyun.utils.PagedGridResult;
import com.xiaoyun.vo.MyCommentVO;
import lombok.RequiredArgsConstructor;
import org.n3r.idworker.Sid;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class MyCommentServiceImpl implements MyCommentService {

    private final OrderItemsMapper orderItemsMapper;

    private final OrdersMapper ordersMapper;

    private final OrderStatusMapper orderStatusMapper;

    private final ItemsCommentsMapperCustom itemsCommentsMapperCustom;


    private final Sid sid;

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public List<OrderItems> queryPendingComment(String orderId) {
        OrderItems query = new OrderItems();
        query.setOrderId(orderId);
        return orderItemsMapper.select(query);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void saveComments(String orderId, String userId, List<OrderItemsCommentBO> commentList) {
        for (OrderItemsCommentBO oic : commentList) {
            oic.setCommentId(sid.nextShort());
        }
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("commentList", commentList);
        itemsCommentsMapperCustom.saveComments(map);

        Orders order = new Orders();
        order.setId(orderId);
        order.setIsComment(YesOrNo.YES.type);
        ordersMapper.updateByPrimaryKeySelective(order);

        OrderStatus orderStatus = new OrderStatus();
        orderStatus.setOrderId(orderId);
        orderStatus.setCommentTime(new Date());
        orderStatusMapper.updateByPrimaryKeySelective(orderStatus);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public PagedGridResult queryMyComments(String userId, Integer page, Integer pageSize) {
        Map<String, Object> map = new HashMap<>();
        map.put("userId",userId);
        PageHelper.startPage(page,pageSize);
        List<MyCommentVO> list = itemsCommentsMapperCustom.queryMyComments(map);
        PagedGridResult gridResult = PagedGridResult.setterPageGrid(list, page);
        return gridResult;
    }
}
